﻿#include "fileutil.h"
#include <model/filemodel.h>
#include <QString>
#include <QTextCodec>


FileUtil::FileUtil() {

}

QList<FileModel*> FileUtil::listDir(QString location) {
    QDir dir(location);
    QList<FileModel*> fileList;

    dir.setFilter(QDir::Dirs | QDir::NoDotAndDotDot);
    QFileInfoList list = dir.entryInfoList();
    for (int i = 0; i < list.size(); ++i) {
        QFileInfo fileInfo = list.at(i);
        fileList.append(new FileModel(fileInfo.fileName(), location + fileInfo.fileName() + "/", "dir", 0));
    }

    dir.setFilter(QDir::Files | QDir::NoDotAndDotDot);
    list = dir.entryInfoList();
    for (int i = 0; i < list.size(); ++i) {
        QFileInfo fileInfo = list.at(i);
        fileList.append(new FileModel(fileInfo.fileName(), location + fileInfo.fileName(), "file", 10));
    }
    return fileList;
}

bool FileUtil::exists(QString location) {
    QFileInfo fi(location);
    return fi.exists();
}

QString FileUtil::readAll(QString path) {
    qDebug() << path;
    QFile loadFile(path);
    if (!loadFile.exists()) {
        qDebug() << "file not exists";
        return "";
    }
    if (!loadFile.open(QIODevice::ReadOnly)) {
        qDebug() << "could't open projects json";
        return "";
    }
    QByteArray allData = loadFile.readAll();
    QTextCodec *tc = QTextCodec::codecForName("UTF8");
    QString str = tc->toUnicode(allData);
    loadFile.close();
    return str;
}

void FileUtil::writeLine(QString filePaht, QString str){
    QString path(filePaht);
    QFile file(path);
    if(!file.exists()){
        file.setFileName(path);
    }

    if(file.open(QIODevice::WriteOnly|QIODevice::Append)){
        file.write((str+"\r\n").toStdString().c_str());
        file.close();
    }
}


